﻿using System.Globalization;
using Contact = ValueConverter2.Models.Contact;

namespace ValueConverter2.Converters;

public class ContactToNameConverter : IValueConverter {
    public object Convert(object value, 
        Type targetType, 
        object parameter,
        CultureInfo culture) {
        return value is Contact contact
            ? $"{contact.FirstName} {contact.LastName}"
            : "";
    }

    public object ConvertBack(object value, 
        Type targetType, 
        object parameter,
        CultureInfo culture) {
        if (value is not string v) {
            return null;
        }

        var split = v.Split(" ");

        if (split.Length < 2) {
            return null;
        }

        return new Contact {
            FirstName = split[0], LastName = split[1]
        };
    }
}